/**
 * ...
 * @author Sergey Mamyan
 */

package tx.squirrel.neko.core;

import haxe.Stack;
import mtwin.web.Request;
import neko.Lib;
import tx.facebook.core.Facebook;

import tx.squirrel.neko.core.handler.FBAppHandler;

import tx.squirrel.neko.core.model.Application;
import tx.squirrel.neko.core.model.Installation;
import tx.squirrel.neko.core.model.Session;
import tx.squirrel.neko.core.model.Config;
import tx.squirrel.neko.core.model.User;
import tx.utils.Utils;

import neko.Sys;
import neko.Web;
import templo.Loader;

import tx.squirrel.neko.core.Database;
import tx.squirrel.neko.core.Engine;

import tx.airclient.dev.FacebookHandler;
import tx.airclient.dev.AdminHandler;

class EngineRequestType {
	public static var WEB:String 		= "web";
	public static var FACEBOOK:String 	= "facebook";
}

class FacebookView {
	public static var PUBLIC:String 	= "public";
	public static var PROFILE:String 	= "profile";
	public static var CANVAS:String 	= "canvas";
	public static var UNKNOWN:String 	= "unknown";
}

class EngineRequest extends Request {
	
	var cookies:Hash<String>;
	
	public function new(){
		super();
		cookies = Web.getCookies();
	}
	
	public function getType():String {
		if (Web.getParams().exists("fb_sig")) {
			return EngineRequestType.FACEBOOK;
		} else {
			return EngineRequestType.WEB;
		}
	}
	
	public function getView():String {
		if 	(this.params.exists("fb_sig_logged_out_facebook") &&
			(this.params.get("fb_sig_logged_out_facebook") == "1")){
			return FacebookView.PUBLIC;
		}else 
		if	(this.params.exists("fb_sig_in_profile_tab") && 
			(this.params.get("fb_sig_in_profile_tab") == "1")) {
			return FacebookView.PROFILE;
		}else
		if 	(this.params.exists("fb_sig_in_canvas") && 
			(this.params.get("fb_sig_in_canvas") == "1")) {
			return FacebookView.CANVAS;
		}else {
			return FacebookView.UNKNOWN;
		}
	}
	
	public function getAppId():String {
		if (this.params.exists("fb_sig_app_id")) {
			return this.params.get("fb_sig_app_id");
		}else {
			return "unknown";
		}
	}
	
	public function getUserId():String {
		if (this.params.exists("fb_sig_profile_user")) {
			return this.params.get("fb_sig_profile_user");
		}else if(this.params.exists("fb_sig_user")){
			return this.params.get("fb_sig_user");
		}else if (this.params.exists("fb_sig_canvas_user")) {
			return this.params.get("fb_sig_canvas_user");
		}else {
			return "unknown";
		}
	}
	
	public function getFriends():Array<String>{
		if (this.params.exists("fb_sig_friends")) {
			return this.params.get("fb_sig_friends").split(",");
		}
		return null;
	}
	
	public function getSessionId():String {
		if (this.params.exists("fb_sig_profile_session_key")) {
			return this.params.get("fb_sig_profile_session_key");
		}else if(this.params.exists("fb_sig_session_key")){
			return this.params.get("fb_sig_session_key");
		}else if (this.params.exists("SID")) {
			return this.params.get("SID");
		}else if (this.cookies.exists("SID")) {
			return this.cookies.get("SID");
		}
		return null;
	}
	
}

class Engine {
	
	public static var request:EngineRequest;
	public static var level:Int;
	
	
	public static function main() {
		
		tx.airclient.dev.FacebookHandler;
		tx.airclient.dev.AdminHandler;
		
		Loader.DEBUG 	= true;
		Loader.TMP_DIR 	= Config.TEMPLATES_DIR;
		Loader.BASE_DIR = Config.TEMPLATES_DIR;
		Loader.MACROS 	= null;
		
		request	= new EngineRequest();
		level = if (request.getPathInfoPart(0) == "index.n") 1 else 0;
		
		Database.open();
		Session.open();
			
		var app:Application = Session.getApp();
		if (app == null) {
			doAuthorize();
		}else {
			app.getHandler().execute(request,level);
		}
		Session.close();
	}
	
	public static function doAuthorize() {
		var appList:List<Application> = Application.manager.all();
		var app:Application = null;
		for (app in appList) {
			trace('<a href="http://www.facebook.com/login.php?v=1.0&api_key='+app.apiKey+'&next=admin">'+app.displayName+'</a>');
		}
	}
	
	public static function handleFacebookRequest() {
		var appId:String 			= Session.session.appId;
		var userId:String 			= Session.session.userId;
		var sessionKey:String 		= Session.session.id;
		
		var view:String 			= request.getView();
		var fbFriends:Array<String> = request.getFriends();
		
		var app:Application 	= Application.manager.getById(appId);
		if (app == null){
			throw "Application not found";
			return;
		}
		
		if (sessionKey == "unknown") {
			if(view == FacebookView.PUBLIC){
				Lib.print('<a href="http://www.facebook.com/login.php?v=1.0&api_key=' + app.apiKey +'">Login</a>');
			}else{
				Lib.print('<fb:redirect url="http://www.facebook.com/login.php?v=1.0&api_key=' + app.apiKey +'"/>');
				return;
			}
		} else {
			Facebook.init(app.apiKey, app.apiSecret, sessionKey);
			
			var user:User = User.register(userId);
			user.update();
			user.updateFriends(fbFriends);
			
			var installation:Installation = Installation.manager.getWithKeys({ appId:app.id, userId:user.id	});
			if (installation == null) {
				installation = Installation.install(app, user);
			}
			installation.update();
			
			var appHandler:FBAppHandler = app.getHandler();
			appHandler.user 			= user;
			appHandler.app 				= app;
			appHandler.installation 	= installation;
			appHandler.session 			= Session.session;
			appHandler.execute(request, level);
		}
		
	}
	
	public static function handleWebRequest() {
		var app:Application = Application.manager.getById(Session.session.appId);
		app.getAdminHandler().execute(request, level);
	}
	
}


